package com.tenement.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tenement.entity.RoleMenu;
import com.tenement.mapper.RoleMenuMapper;
import com.tenement.service.RoleMenuService;
import com.tenement.vo.RoleMenuVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.tenement.entity.table.RoleMenuTableDef.ROLE_MENU;

/**
 *  服务层实现。
 *
 * @author BertXie
 * @since 1.0.1
 */
@Service
@RequiredArgsConstructor
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    private final RoleMenuMapper roleMenuMapper;


    @Override
    public int operator(RoleMenuVo roleMenuVo) {
        List<Long> roleIds = new ArrayList<>();
        roleIds.add(roleMenuVo.getRoleId());
        this.remove(roleIds);
        List<RoleMenu> roleMenus = roleMenuVo.getMenuIds()
                .stream()
                .map(menuId -> RoleMenu.builder().roleId(roleMenuVo.getRoleId()).menuId(menuId).build()).collect(Collectors.toList());
        return roleMenuMapper.insertBatch(roleMenus);
    }

    @Override
    public int remove(List<Long> roleIds) {
        QueryWrapper deleteWrapper = QueryWrapper.create().from(ROLE_MENU).where(ROLE_MENU.ROLE_ID.in(roleIds));
        return roleMenuMapper.deleteByQuery(deleteWrapper);
    }

    @Override
    public int removeByMenuId(Long menuId) {
        QueryWrapper deleteWrapper = QueryWrapper.create().from(ROLE_MENU).where(ROLE_MENU.MENU_ID.eq(menuId));
        return roleMenuMapper.deleteByQuery(deleteWrapper);
    }

    @Override
    public List<Long> menuIds(Long roleId) {
        QueryWrapper queryWrapper = QueryWrapper.create().from(ROLE_MENU)
                .select(ROLE_MENU.MENU_ID)
                .where(ROLE_MENU.ROLE_ID.eq(roleId));
        return roleMenuMapper.selectListByQueryAs(queryWrapper, Long.class);
    }

    @Override
    public List<Long> roleMenus(List<Long> roleIds) {
        return roleMenuMapper.selectListByQueryAs(QueryWrapper.create()
                .from(ROLE_MENU)
                .select(ROLE_MENU.MENU_ID)
                .where(ROLE_MENU.ROLE_ID.in(roleIds)),Long.class);
    }

}
